package com.cat.myblog.common.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.aspectj.lang.JoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LoggingAspect {

    // 定义切点：匹配 com.example.service 包下的所有方法
    @Pointcut("execution(* com.cat.myblog..controller.*.*(..))")
    public void serviceLayer() {}

    // 在方法执行前记录日志
    @Before("serviceLayer()")
    public void logBefore(JoinPoint joinPoint) {
        // 获取当前请求信息
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("即将执行的controller方法: {}", joinPoint.getSignature().toShortString());
        log.info("参数Arguments: {}", (Object) joinPoint.getArgs());
        log.info("访问地址: {}",request.getRequestURL().toString());
    }
    // 在方法成功执行后记录日志
    @AfterReturning(pointcut = "serviceLayer()", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        log.info("controller方法执行成功: {}", joinPoint.getSignature().toShortString());
        log.info("Return value: {}", result);
    }

    // 在方法抛出异常后记录日志
    @AfterThrowing(pointcut = "serviceLayer()", throwing = "exception")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable exception) {
        log.error("Exception in method: {}", joinPoint.getSignature().toShortString());
        log.error("Exception message: {}", exception.getMessage());
    }

    // 在方法执行后记录日志（无论是否抛出异常）
    @After("serviceLayer()")
    public void logAfter(JoinPoint joinPoint) {
        log.info("该方法执行结束 {}", joinPoint.getSignature().toShortString());
    }
}
